package KylinComponents

import (
	"fmt"
	"github.com/go-redis/redis"
	"time"
)

func init() {
	AppRedisConnector()
}

func Get(key string) string {
	stringCmd := ClientRedis.Get(key)
	//fmt.Println(stringCmd.String(), stringCmd.Args(), stringCmd.Val())
	return stringCmd.Val()
}
func Set(key string, value string, exp int) {
	_ = ClientRedis.Set(key, value, time.Duration(exp)*time.Second)
}
func Expire(key string, exp int) {
	result := ClientRedis.Expire(key, time.Duration(exp)*time.Second)
	fmt.Println("redis exp: ", result)
}
func Del(key string) {
	result := ClientRedis.Del(key)
	fmt.Println("redis del: ", result)
}

func Exist(key string) (int64, error) {
	result := ClientRedis.Exists(key)
	return result.Result()
}

var ClientRedis *redis.Client

func AppRedisConnector() {

	cfg := InitConfigFromToml()
	host, _ := cfg.GetValue("APP_REDIS", "host")
	network, _ := cfg.GetValue("APP_REDIS", "network")
	port, _ := cfg.GetValue("APP_REDIS", "port")
	password, _ := cfg.GetValue("APP_REDIS", "password")
	database, _ := cfg.GetValue("APP_REDIS", "database")

	options := redis.Options{
		Network:            network,
		Addr:               host + ":" + port,
		Dialer:             nil,
		OnConnect:          nil,
		Password:           password,
		DB:                 StringToInt(database),
		MaxRetries:         0,
		MinRetryBackoff:    0,
		MaxRetryBackoff:    0,
		DialTimeout:        0,
		ReadTimeout:        0,
		WriteTimeout:       0,
		PoolSize:           0,
		MinIdleConns:       0,
		MaxConnAge:         0,
		PoolTimeout:        0,
		IdleTimeout:        0,
		IdleCheckFrequency: 0,
		TLSConfig:          nil,
		//Limiter:            nil,
	}

	ClientRedis = redis.NewClient(&options)

}
